package com.ios.common.filehanlder;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpLoad {

	public static FileUpLoad getInstance() {
		return new FileUpLoad();
	}

	@SuppressWarnings("unchecked")
	public String fileUpLoad(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Properties prop = new Properties();
		prop.load(Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("./file.properties"));
		// 保存路径
		String filePath = prop.getProperty("file_path");
		// 附件类别索引
		String typeIndex = request.getParameter("ref_lb");
		// 附件类别名称
		String typeValue = "";
		Map<String, List> map = (Map<String, List>) request.getSession().getServletContext().getAttribute("DIC");
		List typeList = map.get("BizQtDic");
		// 创建上传文件路径
		File upDir = new File(filePath);
		if (!upDir.exists()) {
			upDir.mkdirs();
		}
		upDir = new File(filePath+ "\\" + typeValue);
		if(!upDir.exists()){
			upDir.mkdir();
		}
		// 创建临时文件路径
		String tempPath = prop.getProperty("temp_path");
		File tempDir = new File(tempPath);
		if (!tempDir.exists()) {
			tempDir.mkdirs();
		}
		// 保存文件最大值
		long max_size = Integer.parseInt(prop.getProperty("file_max_size")) * 1024 * 1024;
		// 临时文件最大值
		int temp_max_size = Integer.parseInt(prop.getProperty("temp_max_size")) * 1024 * 1024;
		// 设置临时文件配置
		DiskFileItemFactory diskFileFac = new DiskFileItemFactory();
		diskFileFac.setSizeThreshold(temp_max_size);
		diskFileFac.setRepository(new File(tempPath));
		// 设置附件上传配置
		ServletFileUpload fileUp = new ServletFileUpload();
		fileUp.setFileItemFactory(diskFileFac);
		fileUp.setSizeMax(max_size);
		// 获得附件列表
		List fileItems = fileUp.parseRequest(request);
		for (int i = 0; i < fileItems.size(); i++) {
			FileItem fileItem = (FileItem) fileItems.get(i);
			if (fileItem.getSize() < max_size) {
				// 附件的名称
				String fileName = fileItem.getName().substring(
						fileItem.getName().lastIndexOf("\\")+1);
				// 保存之后的附件完整路径
				String fileDir = upDir+"\\"+ UUID.randomUUID().toString()
						+ "_" + fileName;
				fileItem.write(new File(fileDir));
			} else {
				String htmlCode = "<script type=\"text/javascript\" language=\"javascript\">"
						+ "alert('文件"
						+ fileItem.getFieldName()
						+ "超过"
						+ max_size + "兆，无法上传')</script>";
				response.setCharacterEncoding("utf-8");
				response.getWriter().write(htmlCode);
			}
		}
		return "up_success";
	}

}
